# coding=utf-8
import re

import sys

import os

from main.ToolMtkSecurityPatch import get_patch_from_code
from main.ToolMtkSecurityPatch import find_real_git_path


def check_msg(msg=''):
    """检查提交说明是否规范
       符合规范的返回JIRA_KEY
    """

    pattern = r'^<(REQ|BUG|FUNC|DEBUG|PATCH|BASELINE|MERGE)><([A-Z]{2,}\-\d+)><(.+)>$'
    rp = re.compile(pattern)
    if msg.find('Change-Id:') > 0:
        msg = msg.split('Change-Id:')[0].strip()
    m = rp.match(msg)
    if m:
        return m.groups()[1], m.groups()[2]
    else:
        print("\033[43;31;1m提交失败\033[0m")
        print("以下Commit的说明不符合规范:")
        print(u'%s' % msg)
        print('\033[34m标准规范是:<REQ|BUG|FUNC|PATCH|DEBUG><JIRA_KEY><项目tag:说明>\033[0m')
        sys.exit(1)


def adapter_file_name(bin_path, perso_name):
    if perso_name is None:
        print("adapter_file_to_region ERROR perso_name=%s" % perso_name)
        return
    print("adapter_file_to_region perso_name=%s" % perso_name)
    file_list = os.listdir(bin_path)

    old_da_swsec_bin_file = None
    old_efuse_xml_file = None
    for file_name in file_list:
        if "DA_PL_" in file_name and '.bin' in file_name:
            if len(file_name.split('_')) == 3:  # DA_PL_1804.bin
                old_da_swsec_bin_file = file_name
        elif 'efuse_' in file_name and '.xml' in file_name:
            if len(file_name.split('_')) == 2:  # efuse_MT6739.xml
                old_efuse_xml_file = file_name

    if old_efuse_xml_file is not None and old_da_swsec_bin_file is not None:
        new_da_swsec_bin_name = 'DA_SWSEC_%s_%s.bin' % (old_da_swsec_bin_file[6:-4], perso_name)
        os.rename(os.path.join(bin_path, old_da_swsec_bin_file), os.path.join(bin_path, new_da_swsec_bin_name))
        print("adapter_file_to_region rename old DA_PL_*=%s to %s" %
                     (old_da_swsec_bin_file, new_da_swsec_bin_name))

        new_efuse_xml_name = old_efuse_xml_file[:-4] + '_%s.xml' % perso_name
        os.rename(os.path.join(bin_path, old_efuse_xml_file), os.path.join(bin_path, new_efuse_xml_name))
        print("adapter_file_to_region rename efuse_*.xml=%s to %s" % (old_efuse_xml_file, new_efuse_xml_name))
        cmd = "sed -i 's/%s/%s/g' %s" % (old_da_swsec_bin_file, new_da_swsec_bin_name,
                                         os.path.join(bin_path, new_efuse_xml_name))
        ret = os.system(cmd)
        print("adapter_file_to_region replace efuse_file=%s content old=%s new=%s ret=%s" %
                     (old_efuse_xml_file, old_da_swsec_bin_file, new_da_swsec_bin_name, ret))
        if ret is not 0:
                print("replace efuse file DA name failed")


def get_perso_project_info(main_project_name, mab_file_name):
    # mab_file_name = MTK_MT6739_O_C300AE_C300AE_8.1_M30_PR_21_C300AE_8.1_TEST_TEST_TEST_21_01.zip
    # perso_name = C300AE_8.1_TEST_TEST_TEST_18_01
    # project_name: C300AE_8.1_M30_PR_21
    if len(mab_file_name) > 0 and len(main_project_name) > 0:
        info_list = mab_file_name.split(main_project_name)
        if len(info_list) == 2:
            perso_name = os.path.splitext(info_list[-1][1:])[0]
            perso_version = perso_name.split('_')[-1]
            return perso_name, perso_version
    return None, None


def get_main_project_info(custom_file_name):
    # custom_file_name = P200AN_8.1_M30_PR_21_custom.zip
    # project_name: C300AE_8.1_M30_PR_21

    if len(custom_file_name) > 0:
        info_list = custom_file_name.split('_')
        if len(info_list) == 6:
            project_name = custom_file_name[:-len(info_list[-1]) - 1]
            project = info_list[0]
            version = info_list[-2]
            return project_name, project, version
    print('un know format custom name %s' % custom_file_name)
    return None, None, None


if __name__ == '__main__':
    # code_path = "/home/android/Platform/6739O"
    # repo_path = "android/packages"
    # commit_id = "4c98f29e49381692e15dceb7448e1d2d72fcdb88"
    # save_path = "/home/android/Opensource/WorkSpace_Py/SecurityPathTool/temp"
    # ret = get_patch_from_code(code_path, repo_path, commit_id, save_path)
    # print("get_patch_from_code: %s" % ret)
    #
    # repo_path2 = "android/packages/apps/Bluetooth"
    # real_repo_path = find_real_git_path(code_path, repo_path2)
    # print("real_repo_path: " + real_repo_path)
    # dst_repo_name = real_repo_path[len(code_path) + 1:]
    # print("dst_repo_name: " + dst_repo_name)

    # aaa = "<REQ><PCAAO-1924><ALPS03771478 [Google Security Patch][CVE-2017-13252]EoP Vulnerability in Libmediadrm / [Google Security Patch][CVE-2017-13252]EoP Vulnerability in Libmediadrm>"
    # ret = check_msg(aaa)
    # print(ret)

    _project_name = 'P200AN_8.1_M30_PR_21'
    _bin_path = '/home/android/Platform/p200_debug/BUILD_RESULT/P200AN_8.1_M30_PR_21/P200AN_8.1_M30_PR_21_flasher'
    _mba_path = '/home/android/Platform/p200_debug/BUILD_RESULT/P200AN_8.1_M30_PR_21/MTK_MT6739_O_P200AN_P200AN_8.1_M30_PR_21_P200AN_8.1_WIK_FR_OM_21_02.zip'

    _custom_zip_file = '/home/android/Platform/p200_debug/BUILD_RESULT/P200AN_8.1_M30_PR_21/P200AN_8.1_M30_PR_21_custom.zip'
    project_name, project, project_version = get_main_project_info(os.path.basename(_custom_zip_file))
    perso_name, perso_version = get_perso_project_info(project_name, os.path.basename(_mba_path))
    adapter_file_name(_bin_path, perso_name)

